package org.dromara.system.helper;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author chs
 */
@Slf4j
@Component
@Primary
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) throws RuntimeException {
        LoginUser user = LoginHelper.getLoginUser();
        log.info("start insert fill ....");
        if (null != user){
            this.strictInsertFill(metaObject,"createBy",String.class,  user.getUserId().toString());
            this.strictInsertFill(metaObject,"createName",String.class, user.getUsername().toString());
            this.strictInsertFill(metaObject,"tenantId",String.class,user.getTenantId());
            this.strictInsertFill(metaObject,"deptId",Long.class,user.getDeptId());
        }else {
            this.strictInsertFill(metaObject,"createBy",String.class,  "-1");
            this.strictInsertFill(metaObject,"createName",String.class, "-1");
            this.strictInsertFill(metaObject,"tenantId",String.class,"-1");
            this.strictInsertFill(metaObject,"deptId",Long.class,-1L);
        }
        this.strictInsertFill(metaObject,"createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject,"delFlag",String.class,"0");


//        this.strictInsertFill(metaObject,"createBy",String.class,LoginHelper.getUsername());
    }

    @Override
    public void updateFill(MetaObject metaObject) throws RuntimeException{
        LoginUser user = LoginHelper.getLoginUser();
        log.info("start update fill ....");
        if(null != user){
            this.strictUpdateFill(metaObject,"updateBy",String.class, null == user ? "-1" : user.getUserId().toString());
            this.strictUpdateFill(metaObject,"updateName ",String.class, null == user ? "-1" : user.getUsername().toString());
        }
        this.strictUpdateFill(metaObject,"updateTime", LocalDateTime.class, LocalDateTime.now());
//        this.strictUpdateFill(metaObject,"createBy", String.class, LoginHelper.getUsername());

    }
}
